<template>
    <el-container style="height: 700px; border: 1px solid #eee">
        <!--侧边栏-->
        <component-sidebar></component-sidebar>

        <el-container>
            <!--标题-->
            <el-header style="text-align: right; font-size: 12px">
                <h1 id="pageTitle">图书管理系统</h1>
            </el-header>

            <el-main>
                <!--搜索表单-->
                <el-form id="bookSearchForm" :inline="true" :model="formInline" class="demo-form-inline">
                    <el-form-item label="入库人：">
                        <el-input v-model="formInline.depositor" placeholder="入库人"></el-input>
                    </el-form-item>
                    <el-form-item label="是否允许借出：">
                        <el-select v-model="formInline.enableLend" placeholder="是否允许借出">
                            <el-option label="是" value="1"></el-option>
                            <el-option label="否" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态：">
                        <el-select v-model="formInline.status" placeholder="状态">
                            <el-option label="在库中" value="1"></el-option>
                            <el-option label="已借出" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="searchBook">查询</el-button>
                    </el-form-item>
                </el-form>
                <!--数据表格-->
                <el-table
                        :data="tableData"
                        border
                        style="width: 100%"
                        align="center"
                        id="table">
                    <el-table-column
                            prop="id"
                            label="书编"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="cover"
                            label="封面"
                            align="center">
                        <template slot-scope="scope">
                            <img class="bookImg" :src="scope.row.cover" :alt="scope.row.cover">
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="name"
                            label="书名"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="author"
                            label="作者"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="publishingHouse"
                            label="出版社"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="price"
                            label="价格"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="createTime"
                            label="入库时间"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="depositor"
                            label="入库人"
                            align="center">
                    </el-table-column>
                    <el-table-column
                            prop="enableLend"
                            label="允许借出"
                            align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.enableLend === 1">是</span>
                            <span v-else>否</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="status"
                            label="状态"
                            align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.status === 1">在库中</span>
                            <span v-else>已借出</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            fixed="right"
                            label="操作"
                            align="center">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.enableLend === 1 && scope.row.status === 1"
                                       @click="clickBorrow(scope.row)" type="text"
                                       size="small">借出
                            </el-button>
                            <el-button @click="clickUpdate(scope.row)" type="text" size="small">编辑</el-button>
                            <el-button v-if="scope.row.status === 1"
                                       @click="clickDelete(scope.row)" type="text" size="small" style="color: red">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!--分页条-->
                <div class="block">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="pageNation.currentPage"
                            :page-sizes="[5, 10, 20, 30]"
                            :page-size="pageNation.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="pageNation.total">
                    </el-pagination>
                </div>
                <!--删除图书弹窗-->
                <el-dialog title="删除图书" :visible.sync="dialogFormVisible">
                    <el-form :model="deleteBookForm">
                        <el-form-item label="删除原因:"
                                      prop="deleteReason">
                            <el-input v-model="deleteBookForm.deleteReason"
                                      placeholder="请填写删除原因"
                                      maxlength="100"/>
                        </el-form-item>

                        <el-form-item align="center">
                            <el-button type="primary" @click="deleteBook">提交</el-button>
                        </el-form-item>
                    </el-form>
                </el-dialog>

                <!--修改图书弹窗-->
                <el-dialog title="修改图书价格" :visible.sync="updateDialogFormVisible">
                    <el-form :model="updateBookForm">
                        <el-form-item label="价格:"
                                      prop="price">
                            <el-input v-model="updateBookForm.price"
                                      placeholder="请填写新的价格"
                                      maxlength="100"/>
                        </el-form-item>
                        <el-form-item label="是否允许借出："
                                      prop="enableLend">
                            <el-select v-model="updateBookForm.sex" placeholder="请选择是否允许借出">
                                <el-option label="是" value="1"></el-option>
                                <el-option label="否" value="0"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item align="center">
                            <el-button type="primary" @click="updateBook">提交</el-button>
                        </el-form-item>
                    </el-form>
                </el-dialog>

                <!--登记借书弹窗-->
                <el-dialog title="登记借书" :visible.sync="borrowDialogFormVisible">
                    <el-form :model="borrowBookForm">
                        <el-form-item label="姓氏:"
                                      prop="surname">
                            <el-input v-model="borrowBookForm.surname"
                                      placeholder="请填写姓氏"
                                      maxlength="100"/>
                        </el-form-item>
                        <el-form-item label="性别："
                                      prop="price">
                            <el-select v-model="borrowBookForm.sex" placeholder="请选择性别">
                                <el-option label="男" value="男"></el-option>
                                <el-option label="女" value="女"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="手机号码:"
                                      prop="phone">
                            <el-input v-model="borrowBookForm.phone"
                                      placeholder="请填写手机号码"
                                      maxlength="100"/>
                        </el-form-item>
                        <el-form-item label="身份证号:"
                                      prop="idNumber">
                            <el-input v-model="borrowBookForm.idNumber"
                                      placeholder="请填写身份证号"
                                      maxlength="100"/>
                        </el-form-item>

                        <el-form-item align="center">
                            <el-button type="primary" @click="borrowBook">提交</el-button>
                        </el-form-item>
                    </el-form>
                </el-dialog>
            </el-main>

        </el-container>

    </el-container>
</template>

<style>
.el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
}

#pageTitle {
    margin: 0;
    font-size: 40px;
    text-align: center;
}

#insertBtn {
    display: flex;
    float: right;
}

.cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.cover {
    width: 100px;
    height: 100px;
    display: block;
}

.cover-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.cover-uploader .el-upload:hover {
    border-color: #409eff;
}

.bookImg {
    width: 60px;
}

</style>

<script>
import ComponentSidebar from "@/components/ComponentSidebar.vue";
import axios from "axios";

const sendRequestMethod = {
    //发请求查询图书列表
    listBook(pageNation, formInline) {
        let url = "/book/admin/book/list";
        url += ("?categoryId=" + sessionStorage.getItem("categoryId"))
        url += ("&page=" + pageNation.currentPage + "&pageSize=" + pageNation.pageSize);

        if (formInline.depositor != null) {
            url += "&depositor=" + formInline.depositor;
        }
        if (formInline.enableLend != null) {
            url += "&enableLend=" + formInline.enableLend;
        }
        if (formInline.status != null) {
            url += "&status=" + formInline.status;
        }
        try {
            console.log("请求url：" + url);
            axios.get(url, {
                headers: {
                    'token': sessionStorage.getItem("token")
                }
            }).then(
                    (res) => {
                        this.tableData = res.data.data.records;
                        this.pageNation.total = res.data.data.total;
                    }
            ).catch(
                    (err) => {
                        if (err.response.status === 401) {
                            //跳转登录页面
                            this.$router.push("/login");
                        } else {
                            this.openNotification("error", "错误", "查询图书失败");
                        }
                    }
            );
        } catch (error) {
            // 捕获OS错误或其他异常
            //console.error('Caught an error:', error);
            this.openNotification("error", "错误", "查询图书失败!");
        }
    },
}

export default {
    components: {ComponentSidebar},
    data() {
        const item = {
            id: '',
            name: '',
            author: '',
            publishingHouse: '',
            cover: '',
            price: '',
            createTime: '',
            depositor: '',
            enableLend: '',
            status: '',
        };
        return {
            // 表格数据
            tableData: Array(0).fill(item),
            // 搜索表单数据
            formInline: {
                depositor: null,
                enableLend: null,
                status: null,
            },
            //分页条属性
            pageNation: {
                currentPage: 1,
                pageSize: 5,
                total: 0
            },
            // 弹窗
            dialogTableVisible: false,
            dialogFormVisible: false,
            updateDialogFormVisible: false,
            borrowDialogFormVisible: false,
            // 删除图书弹窗表单数据
            deleteBookForm: {
                deleteReason: '',
                row: ''
            },
            //修改图书弹窗表单数据
            updateBookForm: {
                price: 0.0,
                enableLend: null,
                row: ''
            },

            //借书弹窗表单数据
            borrowBookForm: {
                surname: '',
                sex: '',
                phone: '',
                idNumber: '',
                row: ''
            },

            formLabelWidth: '120px',
            imageUrl: '',
        }
    },


    methods: {
        ...sendRequestMethod,

        //点击查询按钮
        searchBook() {
            this.listBook(this.pageNation, this.formInline);
        },

        //分页条pageSize改变
        handleSizeChange(val) {
            this.pageNation.pageSize = val;
            this.listBook(this.pageNation, this.formInline);
        },

        //分页条currentPage改变
        handleCurrentChange(val) {
            this.pageNation.currentPage = val;
            this.listBook(this.pageNation, this.formInline);
        },

        //弹出通知
        openNotification(type, title, message) {
            if (type === "error") {
                this.$notify.error({
                    title: title,
                    message: message
                });
            }

            if (type === "info") {
                this.$notify.info({
                    title: title,
                    message: message
                });
            }

            if (type === "warning") {
                this.$notify.warning({
                    title: title,
                    message: message
                });
            }

            if (type === "success") {
                this.$notify.success({
                    title: title,
                    message: message
                });
            }


        },

        //点击删除按钮
        clickDelete(row) {
            this.deleteBookForm.row = row;
            this.dialogFormVisible = true;
        },

        //删除图书提交
        deleteBook() {
            let url = "/book/admin/book";
            url += ("?id=" + this.deleteBookForm.row.id);
            url += ("&deleteReason=" + this.deleteBookForm.deleteReason);
            axios.delete(url, {
                headers: {
                    'token': sessionStorage.getItem("token"),
                }
            }).then(
                    () => {
                        this.openNotification("success", "成功", "删除图书成功");
                        this.dialogFormVisible = false;
                        this.listBook(this.pageNation, this.formInline);
                    }
            ).catch(
                    (err) => {
                        console.error(err);
                        this.openNotification("error", "错误", "删除图书失败");
                    }
            );
        },

        //点击借书
        clickBorrow(row) {
            this.borrowBookForm.row = row;
            this.borrowDialogFormVisible = true;
        },

        //借书提交
        borrowBook() {
            let url = "/book/admin/borrow";

            let params = {
                bookId: this.borrowBookForm.row.id,
                surname: this.borrowBookForm.surname,
                sex: this.borrowBookForm.sex,
                phone: this.borrowBookForm.phone,
                idNumber: this.borrowBookForm.idNumber,
            };

            axios.put(url, params, {
                headers: {
                    'token': sessionStorage.getItem("token"),
                    'Content-Type': 'application/json'
                }
            }).then(
                    () => {
                        this.openNotification("success", "成功", "借书成功");
                        this.borrowDialogFormVisible = false;
                        this.listBook(this.pageNation, this.formInline);
                    }
            ).catch(
                    (err) => {
                        console.error(err);
                        this.openNotification("error", "错误", "借书失败");
                    }
            );
        },

        //修改图书
        clickUpdate(row) {
            this.updateBookForm.row = row;
            this.updateDialogFormVisible = true;
        },

        //修改图书提交
        updateBook() {
            let url = "/book/admin/book";
            axios.put(url, {
                id: this.updateBookForm.row.id,
                price: this.updateBookForm.price,
            }, {
                headers: {
                    'token': sessionStorage.getItem("token"),
                    'Content-Type': 'application/json'
                }
            }).then(
                    () => {
                        this.openNotification("success", "成功", "修改成功");
                        this.updateDialogFormVisible = false;
                        this.listBook(this.pageNation, this.formInline);
                    }
            ).catch(
                    (err) => {
                        console.error(err);
                        this.openNotification("error", "错误", "修改失败");
                    }
            );
        }
    },

    mounted() {
        try {
            this.listBook(this.pageNation, this.formInline);
        } catch (e) {
            console.error(e);
            this.openNotification("error", "错误", "前端错误")
        }
    }
}
;
</script>
